<?php
namespace app\controller\admin;

use app\BaseController;
use app\model\CustomerGroupModel;
use think\facade\Request;
class CustomerGroup extends BaseController
{

    public function index(){

        // global $_GPC;
        $filter = [];
        if( isset($_GET['name']) ){
            $filter['name'] = $_GET['name'];
        }


        $list = CustomerGroupModel::get_list( $filter );

        return json( $list );

    }

    public function single(){

        $customer_group_id = $_GET['id'];
        $single = CustomerGroupModel::single( $customer_group_id );

        return json( $single );
    }

    public function edit(){

        $res = [
            'status'=>0
        ];
        $id = $_GET['id'] ?: 0;

        $name = Request::param('name');
        $description = Request::param('description');
        $is_default = Request::param('is_default');
        $sort_order = Request::param('sort_order');
        $is_default = intval( $is_default );
        $sort_order = intval( $sort_order );

        //todo 检测用户组名
        $existGroup = CustomerGroupModel::where('name', $name)->findOrEmpty();
        if( !$existGroup->isEmpty() && ($existGroup['id'] != $id) ){

            $res['status'] = 1;
            $res['message'] = '用户组名称已经存在';
            return json( $res );

        }

        $data = [
            'name'=> $name,
            'description'=> $description,
            'is_default'=> $is_default,
            'sort_order'=> $sort_order,
        ];
        //todo  默认值处理
        if( $is_default ){

            CustomerGroupModel::setAllNotDefault( );
        }
        if( empty( $id ) ){
            // $id = CustomerGroupModel::create(  $data );
            $id = CustomerGroupModel::add(  $data );
            $res['status'] = 0;
            $res['id'] = $id;
        }else{

            $ret = CustomerGroupModel::edit( $id, $data );
            $res = [
                'status'=>0,
                'ret'=>$ret
            ];

        }

        return json( $res );

    }

}